<template>
  <div>
    <el-card v-if="examInfo">
      <h1>{{ examInfo.examName }}</h1>
      <p><strong>描述：</strong>{{ examInfo.examDesc }}</p>
      <p><strong>开始时间：</strong>{{ examInfo.startTime }}</p>
      <p><strong>结束时间：</strong>{{ examInfo.endTime }}</p>
      <p><strong>总分：</strong>{{ examInfo.totalScore }}</p>
      <p><strong>及格分数：</strong>{{ examInfo.passScore }}</p>
      <p><strong>考试时长：</strong>{{ examInfo.Duration }} 分钟</p>

      <!-- Countdown Timer -->
      <div class="countdown">
        <p>剩余时间：{{ formattedTime }}</p>
      </div>

      <!-- Questions -->
      <el-card
        v-for="(question, index) in questions"
        :key="question.questionId"
        class="question-card"
      >
        <div class="question-content">
          <p>{{ question.questionContent }}</p>
        </div>

        <!-- Single Choice Questions -->
        <div v-if="question.questionType === 1" class="single-choice">
          <el-radio-group v-model="answers[question.questionId]">
            <el-radio
              v-for="answer in question.answer"
              :key="answer.id"
              :label="answer.id"
              >{{ answer.answer }}</el-radio
            >
          </el-radio-group>
        </div>

        <!-- Multiple Choice Questions -->
        <div v-if="question.questionType === 2" class="multiple-choice">
          <el-checkbox-group v-model="answers[question.questionId]">
            <el-checkbox
              v-for="answer in question.answer"
              :key="answer.id"
              :label="answer.id"
              >{{ answer.answer }}</el-checkbox
            >
          </el-checkbox-group>
        </div>

        <!-- True/False Questions -->
        <div v-if="question.questionType === 3" class="true-false">
          <el-radio-group v-model="answers[question.questionId]">
            <el-radio
              v-for="answer in question.answer"
              :key="answer.id"
              :label="answer.id"
              >{{ answer.answer }}</el-radio
            >
          </el-radio-group>
        </div>

        <!-- Short Answer Questions -->
        <div v-if="question.questionType === 4" class="short-answer">
          <el-input
            type="textarea"
            v-model="answers[question.questionId]"
            rows="4"
            placeholder="Your answer here..."
          ></el-input>
        </div>
      </el-card>

      <!-- Submit Button -->
      <div class="submit-button">
        <el-button type="primary" @click="submitExam">提交答案</el-button>
      </div>
    </el-card>
    <el-message v-else type="warning" description="考试信息加载失败" />

    <!-- Debug Information -->
    <!-- <pre>{{ examInfo }}</pre>
    <pre>{{ questions }}</pre>
    <pre>{{ answers }}</pre> -->
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  getExamInfoById,
  getQuestionById,
  addExamRecord,
} from '@/api/ExamOnline/exam'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()

const examInfo = reactive({
  examId: 0,
  examName: '',
  examDesc: '',
  startTime: '',
  endTime: '',
  totalScore: 0,
  passScore: 0,
  Duration: 0,
})

const questions = ref<any[]>([])
const answers = reactive<Record<number, any>>({})
const timeLeft = ref(0)
let timer: ReturnType<typeof setInterval> | null = null

const formattedTime = computed(() => {
  const minutes = Math.floor(timeLeft.value / 60)
  const seconds = timeLeft.value % 60
  return `${minutes} 分 ${seconds} 秒`
})

onMounted(async () => {
  const examId = Number(route.params.id)
  if (examId) {
    await fetchExamInfo(examId)
    startCountdown(examInfo.Duration * 60)
  } else {
    ElMessage.error('无效的考试 ID')
  }
})

async function fetchExamInfo(id: number) {
  try {
    const { data } = await getExamInfoById(id)
    if (data && data.code === 200) {
      Object.assign(examInfo, {
        examId: data.data.examId,
        examName: data.data.examName,
        examDesc: data.data.examDesc,
        startTime: data.data.startTime,
        endTime: data.data.endTime,
        totalScore: data.data.totalScore,
        passScore: data.data.passScore,
        Duration: data.data.examDuration,
      })

      const questionIds = data.data.questionIds
        .split(',')
        .map((id) => Number(id))
      await fetchQuestions(questionIds)
    } else {
      ElMessage.error('获取考试信息失败')
    }
  } catch (error) {
    console.error('Error fetching exam info:', error)
    ElMessage.error('获取考试信息失败')
  }
}

async function fetchQuestions(questionIds: number[]) {
  const questionsData = await Promise.all(
    questionIds.map(async (id) => {
      try {
        const response = await getQuestionById(id)
        if (response.data && response.data.code === 200) {
          return response.data.data
        } else {
          throw new Error(`问题 ${id} 加载失败`)
        }
      } catch (error) {
        console.error(`Error fetching question ${id}:`, error)
        ElMessage.warning(`问题 ${id} 加载失败`)
        return null
      }
    })
  )

  // Filter out null values
  questions.value = questionsData.filter((data) => data !== null)
}

function startCountdown(duration: number) {
  timeLeft.value = duration
  timer = setInterval(() => {
    timeLeft.value -= 1
    if (timeLeft.value <= 0) {
      clearInterval(timer!)
      submitExam()
    }
  }, 1000)
}

function submitExam() {
  if (timer) clearInterval(timer)

  const questionIds = questions.value.map((q) => q.questionId).join(',')

  const userAnswers = questions.value
    .map((question) => {
      if (question.questionType === 1 || question.questionType === 3) {
        const answer = question.answer.find(
          (a) => a.id === answers[question.questionId]
        )
        return answer ? answer.id : '-'
      } else if (question.questionType === 2) {
        return (answers[question.questionId] || [])
          .map((answerId) => {
            const answer = question.answer.find((a) => a.id === answerId)
            return answer ? answer.id : '-'
          })
          .join('-')
      } else if (question.questionType === 4) {
        return answers[question.questionId] || '-'
      } else {
        return '-'
      }
    })
    .join('-')

  const data = {
    creditImgUrl: '',
    examId: route.params.id,
    questionIds,
    userAnswers,
  }

  console.log('Submitting exam record:', data)

  addExamRecord(data)
    .then((response) => {
      if (response.data.code === 200) {
        ElMessage.success('答案已提交')
        router.push(`/home/result/${examInfo.examId}`)
      } else {
        ElMessage.error('提交失败')
      }
    })
    .catch((error) => {
      console.error('Error submitting exam record:', error)
      ElMessage.error('提交失败')
    })
}
</script>

<style scoped lang="less">
.countdown {
  font-size: 20px;
  color: #ff4d4f;
  margin-bottom: 20px;
}

.questions {
  margin-bottom: 20px;
}

.submit-button {
  text-align: center;
}
</style>
